package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.result.Result;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author lsyandwh
 * @since 2022-12-02
 */
@Api(tags = "用户账户")
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private TransFlowService transFlowService;

    @ApiOperation("账户充值")
    @PostMapping("/commitCharge/{chargeAmt}")
    public Result commitCharge(@PathVariable BigDecimal chargeAmt, HttpServletRequest request){
        String userId = request.getHeader("userId");

        String formStr = userAccountService.commitCharge(chargeAmt,userId);

        return Result.ok().data("formStr",formStr);
    }

    @ApiOperation("异步充值回调")
    @PostMapping("/notify")
    public String userAccountNotify(HttpServletRequest request){

        //获取请求头中所有参数
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());

        if("0001".equals(paramMap.get("resultCode"))){

            //获取订单号
            String transNo = (String) paramMap.get("agentBillNo");

            //幂等性校验
            Boolean b = transFlowService.transNoExists(transNo);
            Assert.isTrue(b, ResponseEnum.EXISTS_TRANS_ERROR);

            String status = userAccountService.userAccountNotify(paramMap);

            return status;
        }else {
            System.out.println("用户充值失败");
            return "success";
        }
    }

    @GetMapping("/getAccount")
    public Result getAccount(HttpServletRequest request){

        String userId = request.getHeader("userId");

        BigDecimal bigDecimal = userAccountService.getAccount(userId);

        return Result.ok().data("account",bigDecimal.doubleValue());
    }
}

